import 'package:find_friend/common/alert_tool.dart';
import 'package:find_friend/common/common_widget.dart' show CustomCircleAvatar;
import 'package:find_friend/const/const.dart';
import 'package:find_friend/network/network.dart';
import 'package:find_friend/pages/im/util/time.dart';
import 'package:find_friend/pages/mine/mine_xspace.dart' show XspaceVoiceView;
import 'package:find_friend/pages/xspace/model/artclemodel.dart';
import 'package:find_friend/pages/xspace/school/view/raise_animated.dart';
import 'package:find_friend/pages/xspace/school/view/xdiscuss_image.dart';
import 'package:flutter/material.dart';

class XdetailDiscussCell extends StatefulWidget {

  final ReplyModel model;
  final Function(bool islike) onLikeAction;
  final Function()  onShouldReloadList;
  final Function(String replyName, String rid) onReply; // 回复评论点击
  final Function() onRefreshData;
  const XdetailDiscussCell({
    Key key, 
    this.model, 
    this.onLikeAction,
    this.onReply,
    this.onRefreshData,
    this.onShouldReloadList
  }) : super(key: key);

  @override
  _XdetailDiscussCellState createState() => _XdetailDiscussCellState();
}

class _XdetailDiscussCellState extends State<XdetailDiscussCell> with SingleTickerProviderStateMixin {

  Animation<double> _animation;
  Animation<double> _scaleAnimation;
  AnimationController _animationController;

  int upvotes = 0;

  @override
  void initState() {
    super.initState();

    _animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 300));
    CurvedAnimation _cureve = CurvedAnimation(parent: _animationController, curve: Curves.bounceIn);
    _animation = Tween<double>(begin: 0, end: 1).animate(_cureve);
    _scaleAnimation = Tween<double>(end: 0.0, begin: 1.0).animate(_cureve);
    if(_islikeFlag()) _animationController.forward(); 
    if(_isdislikeFlag()) _animationController.reverse(); 
  }

  @override
  void didUpdateWidget(XdetailDiscussCell oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 列表刷新的时候会重新走一遍
    if(_islikeFlag()) _animationController.forward(); 
    if(_isdislikeFlag()) _animationController.reverse(); 
  }

  @override
  void dispose() {
    _animationController.dispose();
    super.dispose();
  }

  bool _isdislikeFlag() {
    return widget.model?.dissflag != null;
  }

  bool _islikeFlag() {
    return widget.model?.upvoteflag != null;
  }

  _requestLike(bool islike){
    Networktool.request(API.upvote, params: {"aid": widget.model.id.toString(), "rid": widget.model.id}, method: islike ? NETWORKHTTPMethod.POST : NETWORKHTTPMethod.DELETE, success: (data){
        if(islike){
          upvotes = widget.model.dissflag != null ? 2 : 1;
        } else {
          upvotes = widget.model.upvoteflag != null ? -2 : -1;
        }
        if(islike){
          widget.model.upvoteflag = 1;
          widget.model.dissflag = null;
        } else {
          widget.model.upvoteflag = null;
          widget.model.dissflag = 1;
        }
        setState(() {
          widget.model.upvotes += upvotes;
        });
        islike ? _animationController.forward() : _animationController.reverse();
      if(widget.onShouldReloadList != null) widget.onShouldReloadList();
    }
    ,fail: (msg) => AlertTool.showToast(msg)
    );
  }

  List<Widget> _createReplyList() {
    if(widget.model.reply == null) return [];
    List<Widget> temp = [];
    int length = widget.model.reply.length < 3 ? widget.model.reply.length : 3;
    for(int i=0;i<length;i++){
      temp.add(
        Padding(
          padding: const EdgeInsets.only(top: 5),
          child: RichText(
            text: TextSpan(
              children: [
                TextSpan(text: widget.model.reply[i].remarkname + "：", style: instanceTextStyle(10, APP_main_color)),
                TextSpan(text: _getContenxt(widget.model.reply[i]), style: instanceTextStyle(10, APP_font_black)),
              ]
            ),
          ),
        ),
      );
    }

    if(widget.model.reply.length > 3) {
      temp.add(
        Container(
          padding: const EdgeInsets.only(top: 10),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              Text("${widget.model.reply.length}条回复", style: instanceTextStyle(10, APP_main_color),),
              SizedBox(width: 5,),
              Image.asset("assets/xiayi.png",fit: BoxFit.fill,)
            ],
          ),
        )
      );
    }

    return temp;
  }

  String _getContenxt(ReplyModel sender) {
    String res = "";
    if(sender.photo != null) res += "[图片]";
    if(sender.content != null) res += sender.content;
    if(sender.voice != null) res += "[语音]";
    return res;
  }

  @override
  Widget build(BuildContext context) {

    final size = MediaQuery.of(context).size;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 10),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              InkWell(
                onTap: (){
                  Navigator.of(context).pushNamed("/minepreview", arguments: widget.model.mobile);
                },
                child: CustomCircleAvatar(url: widget.model.avatar, size: 42.h,)
              ),
              SizedBox(width: 8,),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(widget.model.username, style: instanceTextStyle(13, APP_font_black),),
                    Padding(
                      padding: const EdgeInsets.only(right: 50),
                      child: Text("个性签名：${widget.model.bio ?? '这人很懒啥玩意儿没有～'}", maxLines: 1, overflow: TextOverflow.ellipsis, style: instanceTextStyle(9, APP_font_grey),),
                    ),
                  ],
                ),
              ),
              Text(TimeUtil.convertTime(widget.model.createtime * 1000), style: instanceTextStyle(9, APP_font_grey),)
            ],
          ),

          Offstage(
            offstage: widget.model.content == null,
            child: Padding(
              padding: const EdgeInsets.only(left:50),
              child: Text(widget.model.content ?? "", style: instanceTextStyle(14, APP_font_black),),
            ),
          ),

          // 图片
          Offstage(
            offstage: widget.model.photo == null,
            child: Padding(
              padding: EdgeInsets.only(left:50, top: 10,),
              child: XDiscussImagesWidget(list: widget.model.photo ?? [],heroPerfix: "XarticleDetail",)
            ),
          ),

          // 语音
          Offstage(
            offstage: widget.model.voice == null,
            child: Padding(
              padding: const EdgeInsets.only(left:50, top: 10),
              child: XspaceVoiceView(width: size.width * 0.45, voice: widget.model?.voice,),
            ),
          ),
          // 点赞分享按钮
          InkWell(
            onTap: (){},
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                InkWell(
                  onTap: (){
                    if(widget.onReply != null) widget.onReply(widget.model.username, widget.model.id.toString());
                  },
                  child: Container(
                    margin: const EdgeInsets.only(left: 50),
                    padding: const EdgeInsets.symmetric(horizontal: 6.5, vertical: 2),
                    alignment: Alignment.center,
                    decoration: BoxDecoration(
                      border: Border.all(color: APP_divider_color, width: 0.5),
                      borderRadius: BorderRadius.circular(20)
                    ),
                    child: Row(
                      children: [
                        Text("回复", style: instanceTextStyle(10, APP_main_color),),
                        SizedBox(width: 5,),
                        Image.asset("assets/xiayi.png",fit: BoxFit.fill,)
                      ],
                    ),
                  ),
                ),
                Spacer(),
                InkWell(
                  onTap: (){
                    AlertTool.showBottomShareDialog(context, replyModel: widget.model, onRefreshData: widget.onRefreshData);
                  },
                  // child: Image.asset("assets/zhuanfa.png", width: 12,fit: BoxFit.fill,)
                  child: Icon(const IconData(0xe603, fontFamily: "iconfont"), size: 20, color: APP_font_black,),
                ),
                Container(
                  width: 10,
                  alignment: Alignment.centerRight,
                  child: Container(width: 0.5, height: 15, color: APP_divider_color,),
                ),
                InkWell(
                    onTap: () {
                      _requestLike(true);
                    },
                    child: Container(
                      height: 30,
                      width: 30,
                      alignment: Alignment.center,
                      child: RiseAnimatedWidget(
                        dissAnimation: _scaleAnimation, 
                        likeAnimation: _animation,
                        imgW: 20, 
                        iszan: true, 
                        value: _islikeFlag(),
                        fit: BoxFit.scaleDown,
                      ),
                    ),
                  ),
                Container(
                  width: size.width * 0.1 ,
                  alignment: Alignment.center,
                  child: Text("${widget.model?.strUpvotes ?? 0}", style: instanceTextStyle(12, APP_font_black),),
                ),
                InkWell(
                    onTap: () {
                      _requestLike(false);
                    },
                    child: Container(
                      height: 30,
                      width: 30,
                      alignment: Alignment.center,
                      child: RiseAnimatedWidget(
                        dissAnimation: _animation, 
                        likeAnimation: _scaleAnimation,
                        imgW: 20, 
                        iszan: false, 
                        value: _isdislikeFlag(),
                        fit: BoxFit.scaleDown,
                      ),
                    ),
                  ),
              ],
            ),
          ),
          
          Offstage(
            offstage: widget.model.reply == null,
            child: Container(
              margin: const EdgeInsets.only(left: 50, top: 11),
              width: size.width,
              padding: const EdgeInsets.only(top: 5, left: 9.5, right: 9.5, bottom: 10.5),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(5),
                color: APP_scaffold_back_color,
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: _createReplyList(),
              ),
            ),
          ),

          Padding(
            padding: const EdgeInsets.only(top:5.0),
            child: Divider(color: APP_divider_color, height: 0.5,indent: 50,),
          ),
        ],
      ),
    );
  }
}